<?php

namespace App\Http\Controllers\Web\Seller;

use App\ConstDir\ErrorConst;
use App\Events\ItemEvent;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Models\ItemsProducts;
use App\Repository\Models\ItemsStock;
use App\Repository\Models\Shop;
use App\Repository\Models\User;
use App\Repository\Repositories\Interfaces\ItemsInformationRepository;
use App\Repository\Repositories\Interfaces\ItemsProductsRepository;
use App\Repository\Repositories\Interfaces\ItemsStockRepository;
use App\Repository\Repositories\Interfaces\OrdersRepository;
use App\Repository\Repositories\ItemsCrontabsRepositoryEloquent;
use Illuminate\Http\Request;

/**
 *
 * 卖家配单管理
 * @package App\Http\Controllers\Backend
 */
class ItemsInformationController extends BaseController
{
    protected $items;
    protected $request;
    protected $sp_uid;
    protected $shop_id;
    protected $items_crontab;
    protected $del_id;

    public function __construct(ItemsInformationRepository $items,ItemsCrontabsRepositoryEloquent $items_crontab,Request $request)
    {
        parent::__construct();
        $this->request=$request;
        $this->items = $items;
        $this->items_crontab = $items_crontab;
        $this->sp_uid =array_get($this->user, 'id');
        $this->shop_id =array_get($this->user, 'shop_id');
//        //用户只能操作自身所属数据
        $this->items->scopeQuery(function ($query) {
            return $query->where('seller_id',$this->sp_uid);
        });
    }

    public function index()
    {
        $items = $this->items->with(['items_products'])->with(['orders'=>function($sql){
            $sql->select('order_code','order_status');
        }])->paginate($this->perPage);

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $items, true);
    }

    public function show($id){
        $items = $this->items->with(['items_products'])->with(['orders'=>function($sql){
            $sql->select('order_code','order_status');
        }])->find($id);

        $items['data']['quote_contain']=json_decode($items['data']['quote_contain'],true);
        $items['data']['quote_trade']=json_decode($items['data']['quote_trade_time'],true);
        $items['data']['quote_trade_time']=json_decode($items['data']['quote_trade_time'],true);
        if($items['data']['quote_trade_time'][0]==0){
            $items['data']['quote_trade_time']=$items['data']['quote_trade_time'][1];
        }else{
            $items['data']['quote_trade_time']=date('Y-m-d',strtotime($items['data']['created_at'])+$items['data']['quote_trade_time'][0]*60*60*24);
        }
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $items, false);
    }

    /**
     * 创建配单
     * @param ItemsProductsRepository $itemsProduct
     * @return \Illuminate\Support\Collection
     */
    public function store(ItemsProductsRepository $itemsProduct,ItemsCrontabsRepositoryEloquent $itemscrontabs,ItemsStockRepository $stock,OrdersRepository $order){

        $all=$this->request->all();
        $buyer=User::query()->where('phone',$all['buyer_phone'])->get(['id','name','phone'])->toArray();

        if($buyer){
            $buyer_id=$buyer[0]['id'];
        }else{
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
        if($buyer_id==$this->sp_uid){
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
        $quote_trade_time=[
            0=>$all['delivery_time'],
            1=>isset($all['otherTime'])?$all['otherTime']:'',
        ];
        $product=[];
        $other_product=[];
        $goods_total=0;//商品总费用
        $other_total=0;//其它总费用
        if(!empty($all['append_goods_name'])){//商品费用
            foreach($all['append_goods_name'] as $k=>$v){
                $product[$k]['product_name']=$v;
                $product[$k]['brand']=$all['append_goods_brand'][$k];
                $product[$k]['model']=$all['append_goods_model'][$k];
                $product[$k]['num']=$all['append_goods_num'][$k];
                $product[$k]['price']=$all['append_goods_univalent'][$k];
                $product[$k]['total_price']=$all['append_goods_num'][$k]*$all['append_goods_univalent'][$k];
                $product[$k]['type']=1;
                $goods_total+=($all['append_goods_num'][$k]*$all['append_goods_univalent'][$k]);
            }
        }
        if(!empty($all['append_cost_name'])){//其它费用
            foreach($all['append_cost_name'] as $k=>$v){
                $other_product[$k]['product_name']=$v;
                $other_product[$k]['num']=$all['append_cost_num'][$k];
                $other_product[$k]['price']=$all['append_cost_univalent'][$k];
                $other_product[$k]['total_price']=$all['append_cost_num'][$k]*$all['append_cost_univalent'][$k];
                $other_product[$k]['type']=2;
                $other_total+=($all['append_cost_num'][$k]*$all['append_cost_univalent'][$k]);
            }
        }
        $data=[
            'buyer_id'=>$buyer_id,
            'buyer_phone' => $all['buyer_phone'],
            'buyer_contact' =>  $all['buyer_contact'],
            'buyer_company' =>isset($all['buyer_company'])?$all['buyer_company']:'',
            'quote_contain' => json_encode($all['quote_contain']),//报价要素-价格包含
            'seller_phone' =>$all['seller_phone'],
            'seller_contact' => $all['seller_contact'],
            'seller_id' => $this->sp_uid ,
            'seller_company' => $all['seller_company'],
            'project_addr'=>$all['province_text'].$all['city_text'].str_replace($all['province_text'].$all['city_text'],'',$all['address']),
            'quote_trade_time'=> json_encode($quote_trade_time),//报价要素-交货时间
            'product'=>$product,
            'other_product'=>$other_product,
            'goods_total'=>sprintf("%.2f",$goods_total),
            'other_total'=>sprintf("%.2f",$other_total),
            'all_total'=>sprintf("%.2f",$goods_total+$other_total)
        ];
        \DB::beginTransaction();
        try{

            //生成订单
           $order_data=[
               'order_type'=>4,
               'shop_id'=>$this->shop_id,
               'user_id'=>$buyer_id,
               'initial_product_money'=>$data['all_total'],
               'product_money'=>$data['all_total'],
               'order_money'=>$data['all_total'],
               'freight'=>0.00,//实际运费
           ];

           $order_arr=$order->create($order_data);

            $data['item_code']=$order_arr['data']['order_code'];
            $items = $this->items->create($data);

            //生成订单产品
            if(!empty($data['product'])){
                foreach($data['product'] as $k=>$v){
                    $stock_data=[
                        'seller_id'=>$this->sp_uid,
                        'product_name'=>$v['product_name'],
                        'brand'=>$v['brand'],
                        'model'=>$v['model'],
                        'price'=>$v['price'],
                    ];

                    $ItemsStock=ItemsStock::query()->where('product_name',$v['product_name'])->get()->toArray();
                    if($ItemsStock){
                        $Stock_id=$ItemsStock[0]['id'];
                    }else{
                        $stock_add=$stock->create($stock_data);//配单产品表
                        $Stock_id=$stock_add['data']['id'];
                    }
                    $data['product'][$k]['item_id']=$items['data']['id'];
                    $data['product'][$k]['order_id']=$order_arr['data']['id'];
                    $data['product'][$k]['stock_id']=$Stock_id;
                    $itemsProduct->create($data['product'][$k]);//配单订单产品表
                }
            }

            if(!empty($data['other_product'])){
                foreach($data['other_product'] as $k=>$v){
                    $data['other_product'][$k]['item_id']=$items['data']['id'];
                    $data['other_product'][$k]['order_id']=$order_arr['data']['id'];

                    $itemsProduct->create($data['other_product'][$k]);
                }
            }

            //生成配单自动关闭
            $expired_at=time()+60*60*24;//设置自动关闭配单时间为24小时
            $crontab=[
                'expired_at'=>date('Y-m-d H:i:s',$expired_at),
                'order_id'=>$order_arr['data']['id'],
            ];
            $itemscrontabs->create($crontab);
//
            \DB::commit();
        }catch (\Exception $e){
            \DB::rollback(); //事务回滚;
            return $this->error(ErrorConst::FAILED_CODE_MSG);
        }
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $data, false);

    }

    /**
     * 关闭配单
     * @param $id
     */
    public function destroy($id){

        \DB::beginTransaction();
        try {
            // 获取 @table orders_crontabs 信息
            $items=$this->items->with(['orders'])->find($id);
            if(!isset($items['data'])){
                return $this->error('未正确获取到配单',ErrorConst::FAILED_CODE);
            }

            $orders=$items['data']['orders'];
            $order_id=$orders['id'];
            $itamsCrontab = $this->items_crontab->scopeQuery(function($sql)use($order_id){
                return $sql->where('order_id',$order_id);
            })->all();
            $itamsCrontab = $itamsCrontab['data'][0];
            if ($itamsCrontab['status']==1){
                return $this->error('该配单已确认完成',ErrorConst::FAILED_CODE);
            }else{

                // 修改配单状态 && 修改本表状态为已确认
                $confirmEvent = event(new ItemEvent(['order_id' => $order_id]));
                if ($confirmEvent[0]!==true){
                    return $this->error( '配单关闭失败',ErrorConst::FAILED_CODE);
                }
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollback(); //事务回滚;
            return $this->error( '配单关闭失败',ErrorConst::FAILED_CODE);
        }
        return $this->success( '配单关闭成功',ErrorConst::SUCCESS_CODE, false);

        // 返回执行信息

    }

    public function items_count(){
        $data=$this->items->scopeQuery(function($sql){
            return $sql->whereIn('item_status',[0,1])->where('seller_id',$this->sp_uid);
        })->all();
        if($data){
            $data=count($data['data']);
        }else{
            $data=0;
        }
        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $data, false);

    }



}
